# -*- coding: utf-8 -*-
import tkinter as tk
import tkinter.ttk as ttk
from USBDevice import USBDevice
from UARTDevice import UARTDevice
from DeviceManager import set_device,get_device,del_device

class BasicSettingFrame(tk.Frame):
	def __init__(self, *args, **kwargs):
		self.identifier = 'UART1'
		self.device='/dev/cu.usbserial-MLB2A'
		if 'identifier' in kwargs:
			self.identifier=kwargs['identifier']
			del kwargs['identifier']
		if 'device' in kwargs:
			self.device=kwargs['device']
			del kwargs['device']
		super().__init__(*args, **kwargs)
		self.__set_identifier_frame(self.identifier)
		self.__set_device_frame(self.device)

	def __set_identifier_frame(self,identifier='UART1'):
		_tmpFrame=tk.Frame(self)
		tk.Label(_tmpFrame, text='Identifier:',width=9,anchor='e').pack(side='left')
		tk.Label(_tmpFrame, text=identifier).pack(side='left')
		_tmpFrame.pack(anchor='nw')

	def __set_device_frame(self,device='/dev/cu.usbserial-MLB2A'):
		_tmpFrame=tk.Frame(self)
		tk.Label(_tmpFrame, text='Device:',width=9,anchor='e').pack(side='left')
		tk.Label(_tmpFrame, text=device).pack(side='left')
		_tmpFrame.pack(anchor='nw')

	def _set_connect_close_button(self):
		_tmpFrame=tk.Frame(self)
		self.closeButton = tk.Button(_tmpFrame,text='Disconnect')
		self.closeButton.pack(side='left')
		tk.Label(_tmpFrame,width=2).pack(side='left')
		self.openButton = tk.Button(_tmpFrame,text='Connect')
		self.openButton.pack(side='left')
		_tmpFrame.pack(anchor='center',pady=10,padx=10)

	def btnBindCloseAction(self,action):
		self.closeButton.bind('<Button-1>',action)

	def btnBindOpenAction(self,action):
		self.openButton.bind('<Button-1>',action)

class UARTSettingFrame(BasicSettingFrame):
	def __init__(self, *args, **kwargs):
		super().__init__(*args, **kwargs)
		self.__set_baudrate_frame()
		# self.__set_data_bits_Frame()
		# self.__set_parity_Frame()
		# self.__set_stop_bits_Frame()
		# self.__set_flow_control_Frame()
		self._set_connect_close_button()

	def __set_baudrate_frame(self):
		_tmpFrame=tk.Frame(self)
		tk.Label(_tmpFrame, text='Baudrate:',width=9,anchor='e').pack(side='left')
		self.cbBaudrate=ttk.Combobox(_tmpFrame, value=('115200','230400','460800','921600'),width=8)
		self.cbBaudrate.pack(side='left')
		_tmpFrame.pack(anchor='nw')

	def __set_data_bits_Frame(self):
		_tmpFrame=tk.Frame(self)
		tk.Label(_tmpFrame, text='Data Bits:',width=9,anchor='e').pack(side='left')
		self.cbDataBits=ttk.Combobox(_tmpFrame, value=('5','6','7','8'),width=8)
		self.cbDataBits.pack(side='left')
		_tmpFrame.pack(anchor='nw')

	def __set_parity_Frame(self):
		_tmpFrame=tk.Frame(self)
		tk.Label(_tmpFrame, text='Parity:',width=9,anchor='e').pack(side='left')
		self.cbParity=ttk.Combobox(_tmpFrame, value=('None','odd','even'),width=8)
		self.cbParity.pack(side='left')
		_tmpFrame.pack(anchor='nw')

	def __set_stop_bits_Frame(self):
		_tmpFrame=tk.Frame(self)
		tk.Label(_tmpFrame, text='Stop Bits:',width=9,anchor='e').pack(side='left')
		self.cbStopBits=ttk.Combobox(_tmpFrame, value=('1','1.5','2'),width=8)
		self.cbStopBits.pack(side='left')
		_tmpFrame.pack(anchor='nw')

	def __set_flow_control_Frame(self):
		_tmpFrame=tk.Frame(self)
		tk.Label(_tmpFrame, text='Flow Control:',width=9,anchor='e').pack(side='left',anchor='nw')
		_checkButtonFrame = tk.Frame(_tmpFrame)
		self.ctsValue=tk.IntVar()
		self.ctsValue.set(0)
		self.cbCTS=ttk.Checkbutton(_checkButtonFrame,text='CTS',variable=self.ctsValue,onvalue=1,offvalue=0)
		self.cbCTS.pack()
		self.dtrValue=tk.IntVar()
		self.dtrValue.set(0)
		self.cbDTR=ttk.Checkbutton(_checkButtonFrame,text='DTR',variable=self.dtrValue,onvalue=1,offvalue=0)
		self.cbDTR.pack()
		self.xonValue=tk.IntVar()
		self.xonValue.set(0)
		self.cbXON=ttk.Checkbutton(_checkButtonFrame,text='XON',variable=self.xonValue,onvalue=1,offvalue=0)
		self.cbXON.pack()
		_checkButtonFrame.pack(side='left')
		_tmpFrame.pack(anchor='nw')

class USBSettingFrame(BasicSettingFrame):
	def __init__(self, *args, **kwargs):
		super().__init__(*args, **kwargs)
		self._set_connect_close_button()

class DeviceListFrame(tk.Frame):
	def __init__(self,*args,**kwargs):
		super().__init__(*args,**kwargs)
		self.__set_device_frame()

	def get_device_list(self):
		self.deviceList = []
		i=0
		for d in list(UARTDevice.list_device()):
			i += 1
			identifier = 'UART'+str(i)
			self.deviceList.append((identifier,d,'opened' if get_device(identifier) else 'closed'))
		# self.deviceList.append(('USB1','USB0::0x0699::0x0409::C022832::INSTR','closed'))
		# for d in list(USBDevice.list_device()):
		# 	i += 1
		# 	self.deviceList.append(('USB'+str(i),d))

	def __set_device_frame(self):
		_tmpFrame = tk.Frame(self)
		_headers = ['Type','Path','State']
		self.deviceTreeview = ttk.Treeview(_tmpFrame,columns=_headers,show='headings')
		self.deviceTreeview.column('Type',width=80,anchor='w')
		self.deviceTreeview.column('Path',width=300,anchor='w')
		self.deviceTreeview.column('State',width=80,anchor='w')
		self.deviceTreeview.heading('Type',text='Type')
		self.deviceTreeview.heading('Path',text='Path')
		self.deviceTreeview.heading('State',text='State')
		self.get_device_list()
		for item in self.deviceList:
			self.deviceTreeview.insert('','end',values=item)
		self.deviceTreeview.pack(fill=tk.Y,expand=True)
		_tmpFrame.pack(fill=tk.Y,expand=True)

class DeviceSettingToplevel(tk.Toplevel):
	def __init__(self,*args, **kwargs):
		super().__init__(*args, **kwargs)
		#----------
		self.leftFrame = DeviceListFrame(self)
		self.leftFrame.pack(side='left',fill=tk.Y,expand=True)
		self.leftFrame.deviceTreeview.bind("<<TreeviewSelect>>",self.onSelectRow)
		self.rightFrame=None
		self.resizable(0,0)
		self.title('Device Setting')
		self.tree=self.leftFrame.deviceTreeview

	def onSelectRow(self,event):
		rowData = self.leftFrame.deviceTreeview.set(self.leftFrame.deviceTreeview.focus())
		if self.rightFrame:
			self.rightFrame.destroy()
		if rowData['Type'].startswith('UART'):
			self.rightFrame=UARTSettingFrame(self,identifier=rowData['Type'],device=rowData['Path'])
			self.rightFrame.pack()
		if rowData['Type'].startswith('USB'):
			self.rightFrame=USBSettingFrame(self,identifier=rowData['Type'],device=rowData['Path'])
			self.rightFrame.pack()
		if self.rightFrame:
			self.rightFrame.btnBindCloseAction(self.onClick_closeButton)
			self.rightFrame.btnBindOpenAction(self.onClick_openButton)

	def onClick_closeButton(self,event):
		rowData = self.tree.set(self.tree.focus())
		rowID = self.tree.selection()[0]
		self.tree.set(rowID,column='State',value='closed')
		del_device(rowData['Type'])

	def onClick_openButton(self,event):
		rowData = self.tree.set(self.tree.focus())
		rowID = self.tree.selection()[0]
		self.tree.set(rowID,column='State',value='opened')
		identifier = rowData['Type']
		if identifier.startswith('UART'):
			#mark: to do -- create uartdevice instance
			pass
		elif identifier.startswith('USB'):
			#mark: to do -- create usbdevice instance
			pass
		set_device(identifier,"opened_device") # mark: to do

class ScriptEditorTopLevel(tk.Toplevel):
	def __init__(self,*args, **kwargs):
		super().__init__(*args, **kwargs)

class GUIAPP(tk.Tk):
	def __init__(self,*args,**kwargs):
		super().__init__(*args, **kwargs)
		tk.Button(self,text='DeviceSetting',command=self.onclick_DeviceSetting).pack()
		tk.Button(self,text='ScriptEditor',command=self.onclick_ScriptEditor).pack()
		tk.Button(self,text='check_instance',command=self.onclick_CheckInstance).pack()

	def onclick_DeviceSetting(self):
		DeviceSettingToplevel()

	def onclick_ScriptEditor(self):
		ScriptEditorTopLevel()

	def onclick_CheckInstance(self):
		print(get_device('USB1'))
		print(get_device('USB2'))
		print(get_device('USB3'))
		print(get_device('USB4'))
		print(get_device('UART1'))
		print(get_device('UART2'))
		print(get_device('UART3'))


if __name__ == '__main__':
	app=GUIAPP()
	app.mainloop()

